import xml.dom.minidom
import re
import json

class DoXML:
    def __init__(self, xml_file):
        self.doc = xml.dom.minidom.parse(xml_file)

    @staticmethod
    def data_handle(data):
        data = data.replace('\r', '')
        data = data.replace('\t', '')
        data = data.replace('\n', '')
        data = data.replace('&nbsp;', ' ')  # 替换空格
        data = data.replace('&rsquo;', '"')  # 转换中文单引号 ’为英文的 "
        data = data.replace('&lsquo;', '"')  # 转换中文单引号‘ 为英文的 "
        data = data.replace('&ldquo;', '"')  # 转换中文双引号“ 为英文的 "
        data = data.replace('&rdquo;', '"')  # 转换中文双引号 ” 为英文的 "
        data = data.replace('：', ":")  # 转换中文的冒号 ：为英文的冒号 :
        data = data.replace('，', ',')  # 转换中文的逗号 ，为英文的逗号 ,
        data = data.replace('&quot;', '\"')  # 转换 &quot; 为双引号
        data = data.replace('&#39;', '\'')  # 转换 &#39;  为单引号
        data = data.replace('｛', '{')  # 转换中文｛ 为英文的 {
        data = data.replace('｝', '}')  # 转换中文 ｝ 为英文的 }
        data = data.replace('&lt;', '<')  # 转换 &lt; 为 <
        data = data.replace('&gt;', '>')  # 转换 &gt为 >
        data = data.replace('&amp;', '&')
        data = data.replace('【', '[')
        data = data.replace('】', ']')
        # 查找类似这类内容 </pre>、</div> 并替换为空
        result_list = re.findall('</.?>', data)
        if result_list:
            for item in result_list:
                data = data.replace(item, '')
        # 查找类似这类内容 <pre style="background-color:#ffffff;color:#000000;font-family:'宋体';font-size:12pt;">  并替换为空
        result_list = re.findall('<.?[^<]*>', data)
        if result_list:
            for item in result_list:
                data = data.replace(item, '')
        data = data.lstrip()
        return data

    def caseDict(self):
        sheets = {}
        for i in self.doc.childNodes:
            for j in i.childNodes:
                if j.nodeName == 'testsuite':
                    sheet = j.getAttribute('name')
                    testCaseList = j.getElementsByTagName("testcase")
                    sheets[sheet] = testCaseList
                elif j.nodeName == 'testcase':
                    sheet = i.getAttribute('name')
                    testCaseList = i.getElementsByTagName("testcase")
                    sheets[sheet] = testCaseList
        return sheets

    @staticmethod
    def getCase(sheets):
        testCaseDict = {}
        for sheet, caseList in sheets.items():
            case_list = []
            for testCase in caseList:
                case = []
                # 获取到case外部id
                # case_id = DoXML.data_handle(testCase.getElementsByTagName("fullexternalid")[0].childNodes[0].data)
                # name
                name = DoXML.data_handle(testCase.getAttribute("name"))
                # case摘要
                summary = DoXML.data_handle(testCase.getElementsByTagName("summary")[0].childNodes[0].data)
                # case 前提
                preconditions = DoXML.data_handle(testCase.getElementsByTagName("preconditions")[0].childNodes[0].data)
                # case手动or自动
                execution_type = DoXML.data_handle(testCase.getElementsByTagName("execution_type")[0].childNodes[0].data)
                # steps
                steps = testCase.getElementsByTagName("steps")
                # 全部步骤
                steps_list = []
                for step in steps:
                    stepList = step.getElementsByTagName("step")
                    # 添加每一条指令
                    for i in stepList:
                        # 步骤编号
                        step_number = DoXML.data_handle(i.getElementsByTagName("step_number")[0].childNodes[0].data)
                        # 指令
                        actions = DoXML.data_handle(i.getElementsByTagName("actions")[0].childNodes[0].data)
                        # 期望结果
                        expect = i.getElementsByTagName("expectedresults")[0].childNodes
                        if len(expect) == 0:
                            expected = ''
                        else:
                            expected = DoXML.data_handle(expect[0].data)
                        # 手工or自动
                        step_execution_type = i.getElementsByTagName("execution_type")[0].childNodes[0].data
                        st = [step_number] + [actions] + [step_execution_type] + [expected]
                        steps_list.append(st)
                    case = [name] + [summary] + [preconditions] + [execution_type] + [steps_list]
                case_list.append(case)
            testCaseDict[sheet] = case_list
        return testCaseDict

def change_to_json(data):
    with open('1.json','w', encoding='utf-8') as js:
        # data.popitem(data[0])
        for k,v in data.items():
                json.dump(v, js, indent = 1,ensure_ascii=False)

if __name__ == '__main__':
    do_xml = DoXML('WDT.testsuite-deep.xml') #you choice
    xml_data = do_xml.caseDict()
    testCaseData = do_xml.getCase(xml_data)
    change_to_json(testCaseData)
    print(testCaseData)
